# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################


import datetime
import time
from flask import Blueprint, current_app
from flask import request
import utils.pgsql.pgvlogrecord as record
import utils.pgsql.pgtechpay as techpay
from utils.message import response
from utils.wraps import token, urlcost
import utils.pgsql.pgcase
import utils.common.log as log
import json
import hashlib
import random

synchronous_module = Blueprint('synchronous_module', __name__, url_prefix='/synchronous')

#  接收合成记录，同步合成记录信息 Receive synthetic record and synchronize synthetic record information
@synchronous_module.route('/record', methods=['POST'])
@urlcost.cost_count_wraps
def recordSynchronous():
    ret = json.loads(request.data)
    log.logging.info(request.data)
    errorList = []
    pgRecord = record.PgRecord()
    dicMsg = ret['dataList']
    dic = dict()
    case_obj = utils.pgsql.pgcase.PgCase()
    needs_list = ['MediaURLPreview','duration','Status',
                  'createTime','EventTime','ticketPrice',
                  'caseId','caseName','userId']
    for nd in needs_list:
        dic[nd] = dicMsg[nd]
    # 非必要字段
    extra_list = ['ProjectId','operatorId','userName','userId',
                  'activityId','activityName','templateName', 'templateId','photo_url','faceNum']
    for ea in extra_list:
        if ea in dicMsg:
            dic[ea] = dicMsg[ea]
    # 唯一键 ProjectId必要，
    # if not 'ProjectId' in dic:
    #     m5value =  hashlib.md5(dic['MediaURLPreview'].encode(encoding='utf-8')).hexdigest()
    #     dic['ProjectId'] = m5value

    # 唯一键 ProjectId必要, 20230602陆  /synchronous/record 接口 以 视频链接 用户id 创建时间 时长 为联合主键约束相同数据不允许插入
    if not 'ProjectId' in dic:
        m5value = str(dic['MediaURLPreview']) + str(dic['userId'])
        dic['ProjectId'] = m5value

    res = pgRecord.addRecord(dic)
    errorList.append(res)
    if not all(errorList):
        log.logging.error("/synchronous/record write failed ！！！！！！！！！！！！")
    if res:# 成功
        return response.make_response_success(res)
    return response.make_response_3002()

@synchronous_module.route('/pay', methods=['POST'])
@urlcost.cost_count_wraps
def paySynchronous():
    ret = json.loads(request.data)
    log.logging.info(request.data)
    errorList = []
    pgTechpay = techpay.Pgtechpay()
    dicMsg = ret["dataList"]

    dic = dict()
    # dic["payId"] = dicMsg['payId'] #不知道payId
    dic["outTradeNo"] = dicMsg['outTradeNo']
    dic["transactionId"] = dicMsg['transactionId']
    dic["openId"] = dicMsg['openId']
    # dic["productId"] = dicMsg['productId'] if 'productId' in dicMsg else hashlib.md5(
    #                                                                 dicMsg['videoUrl'].encode(encoding='utf-8')
    #                                                                 ).hexdigest()

    dic["productId"] = dicMsg['productId'] if 'productId' in dicMsg else str(dicMsg['videoUrl']) + str(dicMsg['userId'])
    dic["videoUrl"] = dicMsg['videoUrl']
    dic['duration'] = dicMsg['duration']
    dic['thumbImageUrl'] = dicMsg['thumbImageUrl']
    dic["channelId"] = dicMsg["channelId"]
    dic["caseId"] = dicMsg["caseId"]
    dic["createTime"] = dicMsg["createTime"]
    dic['endTime'] = dicMsg['endTime']
    dic['totalFee'] = dicMsg['totalFee']
    dic['cashFee'] = dicMsg['cashFee']
    dic['userId'] = dicMsg['userId']
    dic['people'] = dicMsg['people']   # 推荐人

    dic['templateName'] = dicMsg['templateName']

    extra_keys = ["updateTime", "cloud_url","mch_id"]
    for k in extra_keys:
        if k in dicMsg:
            dic[k] = dicMsg[k]
    res = pgTechpay.addpay(dic)
    if not res:
        # errorList.append(dicMsg['payId'])
        log.logging.error("/synchronous/pay write failed ！！！！！！！！！！！！")
        return response.make_response_400()
    return response.make_response_success(res)


@synchronous_module.route('/pay_cloud_url', methods=['POST'])
@urlcost.cost_count_wraps
def pay_cloud_url():
    # 新增腾讯云cos链接, 异步更新
    ret = json.loads(request.data)
    pgTechpay = techpay.Pgtechpay()
    transactionId = ret["transactionId"]
    cloud_url = ret["cloud_url"]
    res = pgTechpay.update_cloud_url(transactionId,cloud_url=cloud_url)
    if not res:
        log.logging.error("/synchronous/pay_cloud_url update failed ！！！")
        return response.make_response_400()
    return response.make_response_success(res)